package com.seata.demo.storage.controller;

import com.seata.demo.storage.service.StorageService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StorageController {

    @Autowired
    private StorageService storageService;

    /**
     * 扣减库存（AT和XA模式）
     */
    @PostMapping("/storage/deduct")
    public void deduct(@RequestParam("commodityCode") String commodityCode,
                      @RequestParam("count") Integer count) {
        storageService.deduct(commodityCode, count);
    }
    
    /**
     * 恢复库存（Saga补偿）
     */
    @PostMapping("/storage/revert")
    public void revert(@RequestParam("commodityCode") String commodityCode,
                      @RequestParam("count") Integer count) {
        storageService.revert(commodityCode, count);
    }

    /**
     * TCC模式 - 尝试扣减库存
     */
    @PostMapping("/storage/tcc/tryDeduct")
    public boolean tryDeduct(@RequestParam("commodityCode") String commodityCode,
                            @RequestParam("count") Integer count) {
        return storageService.tryDeduct(commodityCode, count);
    }

    /**
     * TCC模式 - 确认扣减
     */
    @PostMapping("/storage/tcc/commit")
    public boolean commit(@RequestBody BusinessActionContext context) {
        String commodityCode = context.getActionContext("commodityCode").toString();
        Integer count = Integer.valueOf(context.getActionContext("count").toString());
        return storageService.confirmDeduct(commodityCode, count);
    }

    /**
     * TCC模式 - 取消扣减
     */
    @PostMapping("/storage/tcc/rollback")
    public boolean rollback(@RequestBody BusinessActionContext context) {
        String commodityCode = context.getActionContext("commodityCode").toString();
        Integer count = Integer.valueOf(context.getActionContext("count").toString());
        return storageService.cancelDeduct(commodityCode, count);
    }
}
